package com.jic.order.controller.manage;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.member.api.rest.MemberInformationApi;
import com.jic.member.request.MeinformationRequest;
import com.jic.order.entity.OrderAfterSaleApplyModel;
import com.jic.order.entity.OrderAfterSaleFlowRecordModel;
import com.jic.order.entity.OrderGoods;
import com.jic.order.entity.OrderPay;
import com.jic.order.enums.AfterSaleStatusEnum;
import com.jic.order.excel.OrderAfterSaleApplyExcelData;
import com.jic.order.mapper.OrderGoodsMapper;
import com.jic.order.request.ModifyOrderStatusRequest;
import com.jic.order.request.OrderAfterSaleApplyBatchRequest;
import com.jic.order.request.OrderAfterSaleApplyRequest;
import com.jic.order.service.OrderAfterSaleApplyService;
import com.jic.order.service.OrderAfterSaleFlowRecordService;
import com.jic.order.service.OrderOperateService;
import com.jic.order.service.OrderPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(value = "订单售后申请", tags = {"订单售后申请"})
@RequestMapping(value = "orderAfterSaleApply")
@RestController
public class OrderAfterSaleApplyController {

	@Autowired
	OrderAfterSaleApplyService orderAfterSaleApplyService;
	@Autowired
	OrderAfterSaleFlowRecordService orderAfterSaleFlowRecordService;
	@Autowired
	OrderPayService orderPayService;
	@Autowired
	OrderOperateService orderOperateService;
	@Resource
	MemberInformationApi memberInformationApi;
	Function<List<OrderAfterSaleApplyModel>, List<OrderAfterSaleApplyExcelData>> toExcelData = (list) -> {
		List<OrderAfterSaleApplyExcelData> excelDataList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(list)) {
			excelDataList = list.stream().map(x -> {
				OrderAfterSaleApplyExcelData data = new OrderAfterSaleApplyExcelData();
				data.setAfterSaleNo(x.getAfterSaleNo());
				data.setOrderNo(x.getOrderNo());
				data.setAuditTime(x.getAuditTime());
				data.setOrderTime(x.getOrderTime());
				data.setRemark(x.getRemark());
				data.setReturnAbsorbAmount(x.getReturnAbsorbAmount());
				data.setReturnAmount(x.getReturnAmount());
				data.setReturnRealAmount(x.getReturnRealAmount());
				return data;
			}).collect(Collectors.toList());
		}
		return excelDataList;
	};
	@Resource
	private OrderGoodsMapper orderGoodsMapper;

	@ApiOperation(value = "订单售后申请", notes = "订单售后申请")
	@RequestMapping(value = "insert", method = RequestMethod.POST)
	public RestResult<String> insert(@RequestBody OrderAfterSaleApplyBatchRequest request) {
		return orderAfterSaleApplyService.orderAfterSaleApplyBatchAdd(request);
	}

	@ApiOperation(value = "订单售后修改", notes = "订单售后修改")
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public RestResult<String> update(@RequestBody OrderAfterSaleApplyBatchRequest request) {
		return orderAfterSaleApplyService.orderAfterSaleUpdate(request);
	}

	@ApiOperation(value = "订单售后申请分页查询", notes = "分页查询订单售后申请")
	@RequestMapping(value = "queryPage", method = RequestMethod.POST)
	public RestResult<PageResult<OrderAfterSaleApplyModel>> queryPage(@RequestBody OrderAfterSaleApplyRequest request) {
		OrderAfterSaleApplyModel model = new OrderAfterSaleApplyModel();
		model.setAdminOperate(request.getAdminOperate());
		model.setAfterSaleNo(StringUtils.isBlank(request.getAfterSaleNo()) ? null : request.getAfterSaleNo());
		model.setAfterSaleType(request.getAfterSaleType());
		model.setStatus(request.getStatus());
		model.setSendBackStatus(request.getSendBackStatus());
		model.setOrderNo(StringUtils.isBlank(request.getOrderNo()) ? null : request.getOrderNo());
		model.setSendBackType(request.getSendBackType());
		model.setReturnDistributor(request.getReturnDistributor());
		model.setReturnNumber(StringUtils.isBlank(request.getReturnNumber()) ? null : request.getReturnNumber());
		model.setMerchantId(request.getMerchantId());
		model.setMemberId(request.getMemberId());
		model.setStoreId(request.getStoreId());
		model.setStoreName(StringUtils.isBlank(request.getStoreName()) ? null : request.getStoreName());
		model.setApplyTimeStart(request.getApplyTimeStart());
		model.setApplyTimeEnd(request.getApplyTimeEnd());
		model.setAfterSalesCompletionTimeStart(request.getAfterSalesCompletionTimeStart());
		model.setAfterSalesCompletionTimeEnd(request.getAfterSalesCompletionTimeEnd());

		Page page = new Page();
		page.setLimit(request.getLimit());
		page.setStart(request.getStart());
		return RestResult.success(orderAfterSaleApplyService.orderAfterSaleApplyQueryPageList(model, page));
	}

	@ApiOperation(value = "订单售后申请详情", notes = "售后申请详情")
	@RequestMapping(value = "detail", method = RequestMethod.POST)
	public RestResult<OrderAfterSaleApplyModel> detail(@RequestBody OrderAfterSaleApplyRequest request) {
		Map map = Maps.newHashMap();
		map.put("id", request.getId());
		map.put("afterSaleNo", request.getAfterSaleNo());
		map.put("orderNo", request.getOrderNo());
		return RestResult.success(orderAfterSaleApplyService.orderAfterSaleApplyQuery(map));
	}

	@ApiOperation(value = "订单售后更新状态", notes = "订单售后更新状态")
	@RequestMapping(value = "updateStatus", method = RequestMethod.POST)
	public RestResult<Integer> updateStatus(OrderAfterSaleApplyRequest request) {
		Map map = Maps.newHashMap();
		map.put("id", request.getId());
		map.put("status", request.getStatus());
		map.put("afterSalesCompletionTime", new Date());
		map.put("auditTime", new Date());
		ModifyOrderStatusRequest request1 = new ModifyOrderStatusRequest();
		request1.setOrderNo(request.getOrderNo());
		request1.setOrderStatus(request.getOrderStatus());
		request1.setOperatorLog(request.getOperatorLog());
		RestResult<String> restResult = orderOperateService.modifyStatus(request1);
		log.info("订单修改状态,返回{}", JSON.toJSONString(restResult));

		// 根据订单号查询商品信息
		OrderGoods orderGoods = orderGoodsMapper.queryGoodsDetails(new OrderGoods() {{
			setOrderNo(request.getOrderNo());
		}});
		// 推送退款售后信息
		MeinformationRequest meinformationRequest = new MeinformationRequest();
		if (AfterSaleStatusEnum.AUDIT_PASS.getCode().equals(request.getStatus())) {
			meinformationRequest.setMemberId(request.getMemberId());
			meinformationRequest.setType(5);
			meinformationRequest.setTitle("您购买的" + orderGoods.getGoodsName() + "售后退款申请审核通过，请邮寄退货商品或等待商家退款。");
			meinformationRequest.setCategory(1);
			memberInformationApi.insertMemberInformation(meinformationRequest);
		}
		if (AfterSaleStatusEnum.AUDIT_REJECT.getCode().equals(request.getStatus())) {
			meinformationRequest.setMemberId(request.getMemberId());
			meinformationRequest.setType(5);
			meinformationRequest.setTitle("您购买的" + orderGoods.getGoodsName() + "售后退款申请审核不通过。您可以重新提交申请或联系平台处理");
			meinformationRequest.setCategory(1);
			memberInformationApi.insertMemberInformation(meinformationRequest);
		}
		return RestResult.success(orderAfterSaleApplyService.orderAfterSaleApplyChangeStatus(map));
	}

	@ApiOperation(value = "获取审核信息", notes = "获取审核信息")
	@RequestMapping(value = "getAuditInfo", method = RequestMethod.POST)
	public RestResult<OrderAfterSaleFlowRecordModel> getAuditInfo(@RequestBody OrderAfterSaleFlowRecordModel request) {
		Page page = new Page();
		page.setStart(0);
		page.setLimit(1000);
		List<OrderAfterSaleFlowRecordModel> rows = orderAfterSaleFlowRecordService.orderAfterSaleFlowRecordQueryPageList(request, page).getRows();
		Optional<OrderAfterSaleFlowRecordModel> first = rows.stream().filter(t -> t.getOperateType() == 1040 || t.getOperateType() == 1050).findFirst();
		return RestResult.success(first.orElseGet(OrderAfterSaleFlowRecordModel::new));
	}

	@ApiOperation(value = "获取操作列表", notes = "获取操作列表")
	@RequestMapping(value = "getOrderAfterSaleFlowRecords", method = RequestMethod.POST)
	public RestResult<List<OrderAfterSaleFlowRecordModel>> getOrderAfterSaleFlowRecords(@RequestBody OrderAfterSaleFlowRecordModel request) {
		Page page = new Page();
		page.setStart(1);
		page.setLimit(1000);
		PageResult<OrderAfterSaleFlowRecordModel> orderAfterSaleFlowRecordModelPageResult = orderAfterSaleFlowRecordService.orderAfterSaleFlowRecordQueryPageList(request, page);
		return RestResult.success(orderAfterSaleFlowRecordModelPageResult.getRows());
	}

	@ApiOperation(value = "获取操作列表分页", notes = "获取操作列表分页")
	@RequestMapping(value = "getOrderAfterSaleFlowRecordsPage", method = RequestMethod.POST)
	public RestResult<PageResult<OrderAfterSaleFlowRecordModel>> getOrderAfterSaleFlowRecordsPage(@RequestBody OrderAfterSaleFlowRecordModel request) {
		Page page = new Page();
		page.setStart(request.getStart());
		page.setLimit(request.getLimit());
		PageResult<OrderAfterSaleFlowRecordModel> orderAfterSaleFlowRecordModelPageResult = orderAfterSaleFlowRecordService.orderAfterSaleFlowRecordQueryPageList(request, page);
		return RestResult.success(orderAfterSaleFlowRecordModelPageResult);
	}

	@ApiOperation(value = "获取支付信息", notes = "获取支付信息")
	@RequestMapping(value = "getOrderPay", method = RequestMethod.POST)
	public RestResult<List<OrderPay>> getOrderPay(@RequestBody OrderPay orderPay) {
		return RestResult.success(orderPayService.query(orderPay));
	}

	@GetMapping("download")
	public void download(HttpServletResponse response, OrderAfterSaleApplyRequest request) {
		request.setStart(1);
		request.setLimit(Integer.MAX_VALUE);
		RestResult<PageResult<OrderAfterSaleApplyModel>> pageResultRestResult = queryPage(request);
		String fileName = "学生信息";
		try {
			fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
		response.setContentType("application/x-download");
		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		try {
			List<OrderAfterSaleApplyExcelData> apply = toExcelData.apply(pageResultRestResult.getData().getRows());
			EasyExcel.write(response.getOutputStream(), OrderAfterSaleApplyExcelData.class).sheet("售后单列表").doWrite(apply);
		} catch (IOException e) {
			log.error("下载失败,e", e);
		}
	}

	@ApiOperation(value = "订单售后退货", notes = "订单售后退货")
	@RequestMapping(value = "exchangeGoods", method = RequestMethod.POST)
	public RestResult exchangeGoods(@RequestBody OrderAfterSaleApplyBatchRequest request) {
		return orderAfterSaleApplyService.exchangeGoods(request);
	}
}
